package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AdminOrderMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.AdminOrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;

/**
 * @program: sky-take-out
 * @description:
 * @author: fmp
 * @create: 2023-04-09 15:10
 * @Version 1.0
 **/
@Service
@Slf4j
public class AdminOrderServiceImpl implements AdminOrderService {
    @Resource
    private AdminOrderMapper adminOrderMapper;
    @Resource
    private OrderDetailMapper orderDetailMapper;
    @Resource
    private OrderMapper orderMapper;


    //条件分页订单查询
    @Override
    public PageResult selectByPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        log.info("=======传递参数useid{}",BaseContext.getCurrentId());
        StringBuilder  orderName = new StringBuilder();
        Page<Orders> ordersList = adminOrderMapper.selectByPage(ordersPageQueryDTO);
        log.error("==查到的订单{}",ordersList.toString());
        List<OrderVO> orderVOList = ordersList.getResult().stream().map(new Function<Orders, OrderVO>() {
            @Override
            public OrderVO apply(Orders orders) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                List<OrderDetail> orderDetails = orderDetailMapper.selectOrdersDetail(orders.getId());
                for (OrderDetail orderDetail : orderDetails) {
                    orderName.append(orderDetail.getName()+"*"+orderDetail.getNumber());
                }
                orderVO.setOrderDishes(String.valueOf(orderName));
                return orderVO;
            }
        }).collect(Collectors.toList());
        log.error("====f分页查询的结果{}",orderVOList.toString());
        return PageResult.builder().total(ordersList.getTotal()).records(orderVOList).build();
    }
    //各个状态的订单数量统计
    @Override
    public OrderStatisticsVO getStatistics() {

        //待派单数量
         Integer confirmed = adminOrderMapper.selectStatisticsConfirmed(Orders.CONFIRMED);
         //派送中
        Integer deliveryInProgress = adminOrderMapper.selectDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);
         //带接单
        Integer toBeConfirmed = adminOrderMapper.selectToBeConfirmed(Orders.TO_BE_CONFIRMED);

        return OrderStatisticsVO.builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed).build();
    }
    //查询订单详情
    @Override
    public OrderVO showOrdersByOrderId(Long id) {
        OrderVO orderVO = new OrderVO();
        Orders orders = orderMapper.selectOrderById(id);
        BeanUtils.copyProperties(orders, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrdersDetail(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }
    //接单
    @Override
    public void confirmOrder( OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = orderMapper.selectOrderById(ordersConfirmDTO.getId());
        if (orders == null || orders.getPayStatus()!=Orders.PAID)
            throw new OrderBusinessException("订单没有结账~");
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        adminOrderMapper.updateOrderStatues(ordersConfirmDTO);
    }
    //拒单
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = orderMapper.selectOrderById(ordersRejectionDTO.getId());
        if (orders == null || orders.getStatus()!=Orders.TO_BE_CONFIRMED)
            throw new OrderBusinessException("订单无法拒绝~");
        orderMapper.updateOrder(Orders.builder().id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .rejectionReason(ordersRejectionDTO.getRejectionReason()).build());
    }
    //取消订单
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancel) {
        Orders orders = orderMapper.selectOrderById(ordersCancel.getId());
        if (orders == null && orders.getStatus()!=Orders.CONFIRMED||orders.getStatus()!=Orders.DELIVERY_IN_PROGRESS)
            throw new OrderBusinessException("无法取消~");
        Orders build = Orders.builder().id(ordersCancel.getId())
                .cancelTime(LocalDateTime.now())
                .cancelReason(ordersCancel.getCancelReason())
                .status(Orders.CANCELLED).build();
        orderMapper.updateOrder(build);
    }
    //完成订单
    @Override
    public void completeOrder(Long id)  {
        Orders orders1 = orderMapper.selectOrderById(id);
        if (orders1==null || orders1.getPayStatus()!=Orders.PAID)
            throw new OrderBusinessException("订单无法完成");
        Orders orders = Orders.builder().id(id).status(Orders.COMPLETED).build();
        orderMapper.updateOrder(orders);
    }
    //派送订单
    @Override
    public void deliveryOrder(Long id) {
        Orders orders1 = orderMapper.selectOrderById(id);
        if (orders1==null || orders1.getStatus()!=Orders.CONFIRMED)
            throw new OrderBusinessException("订单没接单~");
        Orders build = Orders.builder().id(id).status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.updateOrder(build);
    }
}
